<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>列表过滤</title>
    <!-- 引入Vue.js -->
    <script src="../js/vue.js"></script>
  </head>
  <body>
    <!-- 准备好一个容器 -->
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入检索关键字" v-model="keyWord" />
      <ul>
        <!-- 3.直接在v-for循环中使用v-show过滤 -->
        <!-- <li
          v-for="(item,index) of persons"
          v-show="item.name.includes(keyWord)"
          :key="item.id"  
        >
          {{item.name}}-{{item.age}}--{{item.sex}}
       </li> -->
        <li v-for="(item,index) of filPersons" :key="item.id">
          {{item.name}}-{{item.age}}--{{item.sex}}
        </li>
      </ul>
    </div>
  </body>
  <script>
    // 1.用watch实现
/*     const vm = new Vue({
      el: "#root",
      data() {
        return {
          kweyWord: "",
          persons: [
            { id: "001", name: "马冬梅", age: "20", sex: "女" },
            { id: "002", name: "周冬雨", age: "22", sex: "女" },
            { id: "003", name: "周杰伦", age: "25", sex: "男" },
            { id: "004", name: "温兆伦", age: "19", sex: "男" },
          ],
          filPersons: [], // 存储过滤后的数据
        };
      },
      watch: {
        keyWord: {
          immediate: true, // 初始化时先进行一次空内容过滤,获取到全部数据
          // includes("") 返回 0 非 -1
          handler(newValue, oldValue) {
            this.fillPersons = this.persons.filter((p) => {
              // filter过滤器 p为遍历的对象 filter返回过滤后的数组
              return p.name.includes(newValue); // 返回符合条件的新数组
            });
          },
        },
      },
    }); */

    // 2.用computed实现
    const vm = new Vue({
      el: "#root",
      data() {
        return {
          keyWord: "",// 记录搜索输入的关键字
          persons: [
            { id: "001", name: "马冬梅", age: "20", sex: "女" },
            { id: "002", name: "周冬雨", age: "22", sex: "女" },
            { id: "003", name: "周杰伦", age: "25", sex: "男" },
            { id: "004", name: "温兆伦", age: "19", sex: "男" },
          ],
        };
      },
      computed: {
        filPersons() {
          // 将过滤后的数据存储到filPersons中再到页面进行渲染
          return this.persons.filter((p) => {
            // 当参与计算的属性发生改变时会重新执行getter方法
            return p.name.includes(this.keyWord); // filter 返回符合条件的新数组
          });
        },
      },
    });
  </script>
</html>
